package com.cloudcc.mobile.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.StyleRes;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrFrameLayout;
import com.cloudcc.cloudframe.util.GsonUtil;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.entity.AddImageInfo;
import com.cloudcc.mobile.entity.beau.BeauInfoEntity;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.network.QianDaoNewWork;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.view.activity.AtContaxtActivity;
import com.cloudcc.mobile.view.activity.BeauInfoActivity;
import com.cloudcc.mobile.view.fragment.BeauInfoFragment;
import com.google.gson.JsonObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.litesuits.android.log.Log;
import com.mypage.utils.VoiceAudioRecordButton;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * Created by lin on 2017/6/16.
 */

public class BeauInfoFastRecordDialog extends Dialog implements BeauInfoActivity.getUserID {

    private Activity mcontext;
    private View conentView;

    private ImageView btnVoice , leixings , leixing , relevantFasong;
    private VoiceAudioRecordButton button;
    private EditText contextText;
    private RelativeLayout relevent_dibu;

    private int editHeight = 0;
    private int pingmuHeight = 0;
    private int jianpanHeight = 0;
    private boolean mJudge = false;
    private Recorder recorder;
    private String mVoiceTimeLength;
    private String mName;
    private String mVoiceBaseCode , mData;
    private String mType = "amr";
    private String voiceId;
    public String returnCode , mEntityId;
    String contexteditold = null;
    String contexteditnew = null;
    private BeauInfoEntity mBeauInfo1;
    private String mEns = RunTimeManager.getInstance().getlanguage();

    public BeauInfoFastRecordDialog(@NonNull Context context) {
        super(context);
        mcontext = (Activity) context;
    }

    public BeauInfoFastRecordDialog(@NonNull Context context, @StyleRes int theme) {
        super(context, theme);
        mcontext = (Activity) context;

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_fast_send);
        initview();
        setViewLocation();
        setCanceledOnTouchOutside(true);//外部点击取消
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    }


    /**
     * 设置dialog位于屏幕底部
     */
    private void setViewLocation(){
        DisplayMetrics dm = new DisplayMetrics();
        mcontext.getWindowManager().getDefaultDisplay().getMetrics(dm);
        int height = dm.heightPixels;

        Window window = this.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.x = 0;
        lp.y = height;
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // 设置显示位置
        onWindowAttributesChanged(lp);
    }



    public void setdata(BeauInfoEntity mBeauInfo , String mEntityId){
        mBeauInfo1 = mBeauInfo;
        this.mEntityId = mEntityId;
    }

    private void initview() {
        btnVoice = (ImageView) findViewById(R.id.btnVoice);
        button = (VoiceAudioRecordButton) findViewById(R.id.recordButton);
        leixings = (ImageView) findViewById(R.id.leixings);
        leixing = (ImageView) findViewById(R.id.leixing);
        relevantFasong = (ImageView) findViewById(R.id.relevant_fasong);
        contextText = (EditText) findViewById(R.id.context_text);
        relevent_dibu = (RelativeLayout) findViewById(R.id.relevent_dibu);

        contextText.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            //当键盘弹出隐藏的时候会 调用此方法。
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                //获取当前界面可视部分
                ((Activity) mcontext).getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                //获取屏幕的高度
                int screenHeight = ((Activity) mcontext).getWindow().getDecorView().getRootView().getHeight();
                //此处就是用来获取键盘的高度的， 在键盘没有弹出的时候 此高度为0 键盘弹出的时候为一个正数
                int heightDifference = screenHeight - r.bottom;
                pingmuHeight = screenHeight;
                jianpanHeight = heightDifference;
                editHeight = contextText.getHeight();
                Log.d("KeyboardSize", "Size: " + heightDifference + "::" + screenHeight + "::" + contextText.getHeight());
            }
        });

        // 动态改变状态按钮（语音输入和文字输入按钮）
        btnVoice.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (mJudge) {
                    btnVoice.setImageResource(R.drawable.voices);
                    contextText.setVisibility(View.VISIBLE);
                    button.setVisibility(View.INVISIBLE);
                    relevantFasong.setVisibility(View.VISIBLE);
                    mJudge = false;
                } else {
                    btnVoice.setImageResource(R.drawable.keyboards);
                    contextText.setVisibility(View.INVISIBLE);
                    button.setVisibility(View.VISIBLE);
                    relevantFasong.setVisibility(View.GONE);
                    mJudge = true;
                }
            }
        });

        // 这是语音输入 方法 按住说话按钮
        button.setAudioFinishRecorderListener(new VoiceAudioRecordButton.AudioFinishRecorderListener() {

            @Override
            public void onFinished(float seconds, String filePath) {
                dismiss();
                BeauInfoActivity parentActivity = (BeauInfoActivity) mcontext;
                parentActivity.close();

                recorder = new Recorder(seconds, filePath);

                mVoiceTimeLength = setSetTimeInt(String.valueOf(recorder.time));// 语音时间长度

                mName = UUID.randomUUID().toString();// 给语音文件随机起名字

                try {
                    String dir = Environment.getExternalStorageDirectory()
                            + "/yuyina";// 创建文件夹
                    File files = new File(dir);
                    if (!files.exists()) {
                        files.mkdirs();
                    }
                    mVoiceBaseCode = encodeBase64File(filePath);// 转换成Base64码
                    File filea = new File(files, "hha.amr");
                    // 将base64字符解码成语音保存文件
                    // decoderBase64File(String.valueOf(encodeBase64File(filePath)),filea);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                // 播放音频
                String dira = Environment.getExternalStorageDirectory()
                        + "/yuyina/hha.amr";// 创建文件夹
                createJson();
                sendVoice(mData);// 发送语音

            }

            private String setSetTimeInt(String timeLength) {
                // TODO Auto-generated method stub
                String s = timeLength;// 获取语音时间
                BigDecimal bg = new BigDecimal(s);
                double fTime = bg.setScale(1, BigDecimal.ROUND_DOWN)
                        .doubleValue();
                int round = (int) Math.round(fTime);
                return String.valueOf(round);
            }
        });


        relevantFasong.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = contextText.getText().toString().trim();
                if (name.equals("")) {

                    if ("en".equals(mEns)) {
                        Tools.showInfo(mcontext, "The content can not be blank！");
                    } else {
                        Tools.showInfo(mcontext, "内容不能为空！");
                    }

                    // Tools.showInfo(mContext, String.valueOf(getLeng(dir,"lyj.amr")));
                    return;
                }
                List<AddImageInfo> list = new ArrayList<AddImageInfo>();
                QianDaoNewWork qiandao = new QianDaoNewWork(mcontext, Tools.getNum());
                String typeaa = "汇报记录";
                String relevantName;
                try {
                    JsonObject jsonObject = mBeauInfo1.recordInformationList.get(0);// 详情对象
                    relevantName = typeaa + "【"
                            + GsonUtil.getStringByJson("name", jsonObject) + "】";
                    AppContext.relevantName = GsonUtil.getStringByJson("name",
                            jsonObject);
                } catch (Exception e) {
                    relevantName = typeaa;
                    e.printStackTrace();
                }
                BeauInfoActivity parentActivity = (BeauInfoActivity) mcontext;
                parentActivity.close();
                qiandao.QiaoDaoChatputong(null, mEntityId, relevantName, list, name,
                        "1", "汇报记录");
                contextText.setText("");
                dismiss();
            }
        });


        contextText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
                Log.d("textchangeo", "nnnnn" + contextText.getText());

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {
                Log.d("textchangeo", "bbbbb" + contextText.getText());
                contexteditold = contextText.getText().toString().trim();
            }

            @Override
            public void afterTextChanged(Editable arg0) {
                contexteditnew = contextText.getText().toString().trim();
                if (contexteditnew.length() > contexteditold.length()) {
                    if (contextText.getText().toString().endsWith("@")) {
                        Log.d("textchangeo", "aaaaa" + contextText.getText());

                        String neirong = contextText.getText().toString()
                                .trim();
                        String neirong1 = neirong.substring(0,
                                neirong.length() - 1);
                        contextText.setText(neirong1);
                        Intent intent = new Intent(mcontext,
                                AtContaxtActivity.class);
                        mcontext.startActivityForResult(intent, 2222);
                    }
                }
            }
        });


    }


    // amr转Base64
    public String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return Base64.encodeToString(buffer, Base64.DEFAULT);
    }

    // 把数据转换成json格式。用于上传服务端
    public void createJson() {
        JSONObject object = new JSONObject();

        try {
            object.put("YYData", mVoiceBaseCode);
            object.put("YYName", mName);
            object.put("YYType", mType);
            object.put("YYTimeLength", mVoiceTimeLength);
            object.put("recordId", mEntityId);
            mData = object.toString();

            System.out.println(object);
            // Log.d("/////////////////", object.toString());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // 访问网络发送语音
    public void sendVoice(String mData) {
        // Log.d("lyj", UrlManager.getInterfaceUrl()+"?data="+mData+"&"+
        // RunTimeManager.getInstance().getServerBinding()+"&"+"serviceName="+"uploadYY");

        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        // params.addBodyParameter("userId",UserManager.getManager().getUser().userId);
        params.addBodyParameter("data", mData);
        params.addBodyParameter("binding", RunTimeManager.getInstance()
                .getServerBinding());
        params.addBodyParameter("serviceName", "uploadYY");

        Log.d("request----", "发送语音  url   " + UrlManager.getInterfaceUrl()
                + "?binding=" + RunTimeManager.getInstance().getServerBinding()
                + "&" + "serviceName=" + "uploadYY" + "&data=" + mData);

        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        // TODO Auto-generated method stub
                        Log.d("request----", "上传语音Failure。。。" + arg1);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        // TODO Auto-generated method stub
                        String result = arg0.result;
                        Log.d("request----", "上传语音Success:     " + result);
                        parseJson(result);
                    }

                });

    }

    private void parseJson(String result) {
        // TODO Auto-generated method stub
        JSONObject parseJson = null;
        try {
            parseJson = new JSONObject(result);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            String sssa = voiceId;
            voiceId = parseJson.getJSONObject("data").optString("id");
            returnCode = parseJson.getString("returnCode");
            if (returnCode.equals("1")) {
                Toast.makeText(mcontext, mcontext.getString(R.string.yuyin_success), Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(AppContext.INDEXADAPTER_SHUAXIN);
                mcontext.sendBroadcast(intent);
            } else {
                Toast.makeText(mcontext, mcontext.getString(R.string.yuyin_fail), Toast.LENGTH_SHORT).show();
            }
            downLoadVoice(voiceId);
            sssa = "q";
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /*
    * 测试下载语音
    */
    public void downLoadVoice(String voiceId) {
        // Log.d("lyj", UrlManager.getInterfaceUrl()+"?data="+mData+"&"+
        // RunTimeManager.getInstance().getServerBinding()+"&"+"serviceName="+"uploadYY");

        HttpUtils utils = new HttpUtils();
        RequestParams params = new RequestParams();
        // params.addBodyParameter("userId",UserManager.getManager().getUser().userId);
        params.addBodyParameter("binding", RunTimeManager.getInstance()
                .getServerBinding());
        params.addBodyParameter("serviceName", "downloadYY");
        params.addBodyParameter("id", voiceId);
        Log.d("request----", "下载语音 url ==   " + UrlManager.getInterfaceUrl()
                + "?binding=" + RunTimeManager.getInstance().getServerBinding()
                + "&" + "serviceName=" + "downloadYY" + "&id=" + voiceId);

        utils.send(HttpRequest.HttpMethod.POST, UrlManager.getInterfaceUrl(), params,
                new RequestCallBack<String>() {

                    @Override
                    public void onFailure(HttpException arg0, String arg1) {
                        // TODO Auto-generated method stub
                        Log.d("request----", "Failure。。。" + arg1);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> arg0) {
                        // TODO Auto-generated method stub
                        String result = arg0.result;
                        Log.d("request----", "Success_down_voice:     "
                                + result);
                        getId(result);
                    }

                });

    }

    private void getId(String result) {
        // TODO Auto-generated method stub
        JSONObject getId = null;
        try {
            getId = new JSONObject(result);
            JSONObject upYY = getId.getJSONObject("data");
            String getID = upYY.getString("id");// 这是要上传的ID
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void getUser(String userName) {
        contextText.append(userName);
    }

    /**
     * 这是内部类
     */
    class Recorder {
        float time;
        String filePathString;

        public Recorder(float time, String filePathString) {
            super();
            this.time = time;
            this.filePathString = filePathString;
        }

        public float getTime() {
            return time;
        }

        public void setTime(float time) {
            this.time = time;
        }

        public String getFilePathString() {
            return filePathString;
        }

        public void setFilePathString(String filePathString) {
            this.filePathString = filePathString;
        }

    }
}
